﻿using System;
using System.Collections.Generic;
using System.IdentityModel.Tokens.Jwt;
using System.Linq;
using System.Security.Claims;
using System.Threading.Tasks;
using LinqKit;
using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Cors;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc;
using Microsoft.Data.SqlClient;
using Microsoft.EntityFrameworkCore;
using Microsoft.Extensions.Configuration;
using Microsoft.IdentityModel.Tokens;
using QualitySupervision.Core;
using QualitySupervision.Models;

namespace QualitySupervision.Controllers
{
    //[Route("api/[controller]")]
    [Route("api/")]
    [ApiController]
    public class LoginController : Controller
    {
        private readonly ApiDBContent _dbContext;
        private readonly IConfiguration _configuration;

        public LoginController(ApiDBContent dbContext, IConfiguration configuration)
        {
            _dbContext = dbContext;
            _configuration = configuration;
        }

        /// <summary>
        /// 登录
        /// </summary>
        /// <param name="user"></param>
        /// <returns></returns>
        [HttpPost("Login")]
        public IActionResult Login([FromBody] User user)
        //public IActionResult login(string username, string password)
        {
            ////执行查询SQL语句
            //var count = _dbContext.Database.SqlQuery<User>(@"select * from [Users] where username=@username and password=@password", new[] {
            //    new SqlParameter("@username", username),
            //    new SqlParameter("@password", password)
            //});
            //HttpContext.Response.Headers.Add("Access-Control-Allow-Origin", "*");
            var count2 = _dbContext.Users
                .Where(x=>x.username== user.username && x.password == user.password)
                .SingleOrDefault();

            //string msg = "msg = 200, msg='登录失败'";
            var msg1 = new { msg= "登录成功", status = 200 };
            var msg2 = new { msg = "登录失败", status = 404 };

            if (count2 is null)
            {
                return Json(new { meta = msg2 });
            }
            else
            {
                //获取rightid---------------
                var rightids = _dbContext.roles.Find(count2.rid);
                //--------------------------
                var tokenParameter = _configuration.GetSection("tokenParameter").Get<TokenParameter>();
                var claims = new Claim[]
                {
                     new Claim(ClaimTypes.Name,user.username),
                     new Claim(ClaimTypes.Role,"Root"),
                };
                var key = new SymmetricSecurityKey(System.Text.Encoding.UTF8.GetBytes(tokenParameter.Secret));
                var token = new JwtSecurityToken(
                            issuer: tokenParameter.Issuer,
                            audience: tokenParameter.Audience,
                            claims: claims,
                            notBefore: DateTime.Now,
                            expires: DateTime.Now.AddMinutes(tokenParameter.AccessExpiration),
                            signingCredentials: new SigningCredentials(key, SecurityAlgorithms.HmacSha256));

                //生成Token
                string jwtToken = new JwtSecurityTokenHandler().WriteToken(token);
                jwtToken = "bearer " + jwtToken;
                var msg3 = new { id= count2.ID, count2.rid, count2.username, count2.mobile, count2.email, count2.dept, count2.deptmentname,count2.departmentId, count2.name, count2.role_name, token = jwtToken, rightids };
                //string a = msg3.GetType().ToString();

                return Json(new { meta = msg1, data = msg3 });
            }
            


            ////lamda多条件组合查询

            ////方法一：
            ////可以看到，查询条件多的话，我们会写很多的if判断，代码看起来很不美观
            //*
            //var blogs = _dbContext.Blogs.Where(s => (blogIds.Length > 0 || blogIds.Contains(s.Id)) &&
            //                                                                      (string.IsNullOrEmpty(title) || s.Title.Contains(title))
            //                                                                     )
            //                                                .Select(s => s)
            //                                                .OrderBy(o => o.Id);
            //*

            ////方法二：Using PredicateBuilder
            ////LinqKit.Microsoft.EntityFrameworkCore
            ////https://github.com/scottksmith95/LINQKit
            //var predicate = PredicateBuilder.New<User>(true); //Expression<Func<Blog, bool>> predicate = c => true;

            //if (username?.Length > 0)
            //{
            //    predicate = predicate.And(p => username.Contains(p.username));
            //}

            //if (!string.IsNullOrEmpty(password))
            //{
            //    predicate = predicate.And(p => p.password.Contains(password));
            //}

            //var blogs = _dbContext.Users.Where(predicate).Select(s => s).OrderBy(o => o.ID);

            ////var data = await PaginatedList<Blog>.CreatePagingAsync(blogs, pageIndex, pageSize);
            ////return Json(new { code = 200, msg = "ok", data = data });
        }
    }
}
